<?php
/**
 * Resort
 * Класс Resort отвечает за обработку курортов
 * @author Sayp
 */
class Resort extends ActiveRecord {
	protected static $_tableName = 'resort';
	protected static $_pkName = 'ID_resort';
	
	protected static $_essenceType = 3;
	
	protected function afterValidation() {
		$objDB = Service_Database::instance();
		$stmt = "SELECT `ID_resort` FROM `resort` WHERE `resort_url` = '" . $this->getField('resort_url') . "'";
		if ($this->id) $stmt .= ' AND `ID_resort` != ' . $this->id;
		if ($objDB->isRecordExist($stmt)) $this->arrErrors = 'Такой url уже используется';
	}
	
	public function getWeather() {
		if (!$this->id) return array();
	
		$objDB = Service_Database::instance();
	
		$arrWeather = $objDB->select('
			SELECT round(AVG(`daily_temp`)) as `temp`, MONTH(`date`) as `month`
			FROM `weather`
			WHERE `ID_resort` = ' . $this->id . '
			GROUP BY `month`
			ORDER BY `month`
		');
		
		if (!empty($arrWeather)) $arrWeather = Service_ArrayConverter::makeKeyFromColumn($arrWeather, 'month');
		
		return $arrWeather;
	}
	
	public function getOtherResorts($limit = 2) {
		if (!$this->id) return array();
		
		return $this->find('all', array(
			'conditions' => '`ID_resort` != ' . $this->id,
			'order' => 'ABS(CAST(`ID_country` as SIGNED) - ' . $this->getField('ID_country') . ') ASC',
			'limit' => $limit
		));
	} 
}